import React, { useState } from 'react';
import { PerformanceMonitor } from '../components/PerformanceMonitor';
import {
  usePerformanceMonitor,
  usePerformanceEvent,
  useCustomMetrics,
  usePerformanceReport,
} from '../hooks/usePerformance';
import {
  ChartBarIcon,
  PlayIcon,
  StopIcon,
  ClockIcon,
  CpuChipIcon,
  DocumentChartBarIcon,
} from '@heroicons/react/24/outline';

const Performance: React.FC = () => {
  const [activeTab, setActiveTab] = useState<
    'monitor' | 'events' | 'metrics' | 'report'
  >('monitor');

  const {
    metrics,
    history,
    isMonitoring,
    startMonitoring,
    stopMonitoring,
    clearHistory,
    collectMetrics,
  } = usePerformanceMonitor({ autoStart: true });

  const { activeEvents, completedEvents, startEvent, endEvent, measure } =
    usePerformanceEvent();

  const { setMetric, incrementMetric } = useCustomMetrics();
  const { report, generateReport, clearData } = usePerformanceReport();

  // 事件管理状态
  const [eventName, setEventName] = useState('');
  const [eventMetadata, setEventMetadata] = useState('{}');

  // 自定义指标状态
  const [metricName, setMetricName] = useState('');
  const [metricValue, setMetricValue] = useState('');

  const handleStartEvent = async () => {
    if (!eventName.trim()) return;

    try {
      const metadata = JSON.parse(eventMetadata);
      await startEvent(eventName, metadata);
      setEventName('');
      setEventMetadata('{}');
    } catch (error) {
      alert('元数据格式错误，请输入有效的 JSON');
    }
  };

  const handleSetMetric = async () => {
    if (!metricName.trim() || !metricValue.trim()) return;

    try {
      const value = parseFloat(metricValue);
      if (isNaN(value)) {
        alert('请输入有效的数值');
        return;
      }

      await setMetric(metricName, value);
      setMetricName('');
      setMetricValue('');
    } catch (error) {
      alert('设置指标失败');
    }
  };

  const handleIncrementMetric = async (name: string) => {
    try {
      await incrementMetric(name, 1);
    } catch (error) {
      alert('增加指标失败');
    }
  };

  const testPerformanceEvent = async () => {
    await measure(
      'test_operation',
      async () => {
        // 模拟一些工作
        await new Promise(resolve =>
          setTimeout(resolve, Math.random() * 1000 + 500)
        );
      },
      { type: 'test', user_initiated: true }
    );
  };

  const tabs = [
    { id: 'monitor', name: '实时监控', icon: ChartBarIcon },
    { id: 'events', name: '事件追踪', icon: ClockIcon },
    { id: 'metrics', name: '自定义指标', icon: CpuChipIcon },
    { id: 'report', name: '性能报告', icon: DocumentChartBarIcon },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
            性能监控
          </h1>
          <p className="mt-1 text-gray-600 dark:text-gray-400">
            实时监控系统性能指标 (数据点: {history.length})
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <button
            onClick={() => collectMetrics()}
            className="flex items-center rounded bg-blue-600 px-3 py-2 text-white hover:bg-blue-700"
            title="手动收集性能数据"
          >
            <ChartBarIcon className="mr-2 h-4 w-4" />
            收集数据
          </button>

          <button
            onClick={clearHistory}
            className="flex items-center rounded bg-gray-600 px-3 py-2 text-white hover:bg-gray-700"
            title="清除历史数据"
          >
            清除历史
          </button>

          <button
            onClick={isMonitoring ? stopMonitoring : startMonitoring}
            className={`flex items-center rounded px-4 py-2 ${
              isMonitoring
                ? 'bg-red-600 text-white hover:bg-red-700'
                : 'bg-green-600 text-white hover:bg-green-700'
            }`}
          >
            {isMonitoring ? (
              <>
                <StopIcon className="mr-2 h-4 w-4" />
                停止监控
              </>
            ) : (
              <>
                <PlayIcon className="mr-2 h-4 w-4" />
                开始监控
              </>
            )}
          </button>
        </div>
      </div>

      {/* 标签页导航 */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="-mb-px flex space-x-8">
          {tabs.map(tab => {
            const IconComponent = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`flex items-center border-b-2 px-1 py-2 text-sm font-medium ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                    : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
                }`}
              >
                <IconComponent className="mr-2 h-4 w-4" />
                {tab.name}
              </button>
            );
          })}
        </nav>
      </div>

      {/* 标签页内容 */}
      <div className="mt-6">
        {activeTab === 'monitor' && (
          <PerformanceMonitor showDetails={true} autoRefresh={isMonitoring} />
        )}

        {activeTab === 'events' && (
          <div className="space-y-6">
            {/* 事件控制 */}
            <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
              <h2 className="mb-4 text-lg font-semibold">事件管理</h2>

              <div className="mb-4 grid grid-cols-1 gap-4 md:grid-cols-2">
                <div>
                  <label className="mb-2 block text-sm font-medium">
                    事件名称
                  </label>
                  <input
                    type="text"
                    value={eventName}
                    onChange={e => setEventName(e.target.value)}
                    placeholder="输入事件名称"
                    className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
                  />
                </div>
                <div>
                  <label className="mb-2 block text-sm font-medium">
                    元数据 (JSON)
                  </label>
                  <input
                    type="text"
                    value={eventMetadata}
                    onChange={e => setEventMetadata(e.target.value)}
                    placeholder='{"key": "value"}'
                    className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
                  />
                </div>
              </div>

              <div className="flex space-x-2">
                <button
                  onClick={handleStartEvent}
                  disabled={!eventName.trim()}
                  className="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:opacity-50"
                >
                  开始事件
                </button>
                <button
                  onClick={testPerformanceEvent}
                  className="rounded bg-green-600 px-4 py-2 text-white hover:bg-green-700"
                >
                  测试事件
                </button>
              </div>
            </div>

            {/* 活跃事件 */}
            <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
              <h2 className="mb-4 text-lg font-semibold">
                活跃事件 ({activeEvents.length})
              </h2>

              {activeEvents.length === 0 ? (
                <p className="text-gray-500 dark:text-gray-400">
                  没有活跃的事件
                </p>
              ) : (
                <div className="space-y-2">
                  {activeEvents.map(event => (
                    <div
                      key={event.id}
                      className="flex items-center justify-between rounded-lg bg-yellow-50 p-3 dark:bg-yellow-900/20"
                    >
                      <div>
                        <div className="font-medium">{event.name}</div>
                        <div className="text-sm text-gray-600 dark:text-gray-400">
                          开始时间:{' '}
                          {new Date(event.start_time).toLocaleTimeString()}
                        </div>
                      </div>
                      <button
                        onClick={() => endEvent(event.id)}
                        className="rounded bg-red-600 px-3 py-1 text-sm text-white hover:bg-red-700"
                      >
                        结束
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* 已完成事件 */}
            <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
              <h2 className="mb-4 text-lg font-semibold">最近完成的事件</h2>

              {completedEvents.length === 0 ? (
                <p className="text-gray-500 dark:text-gray-400">
                  没有已完成的事件
                </p>
              ) : (
                <div className="space-y-2">
                  {completedEvents.slice(0, 10).map((event, index) => (
                    <div
                      key={index}
                      className="rounded-lg bg-green-50 p-3 dark:bg-green-900/20"
                    >
                      <div className="flex items-start justify-between">
                        <div>
                          <div className="font-medium">{event.name}</div>
                          <div className="text-sm text-gray-600 dark:text-gray-400">
                            持续时间: {event.duration?.toFixed(2)}ms
                          </div>
                        </div>
                        <div className="text-xs text-gray-500 dark:text-gray-400">
                          {new Date(event.start_time).toLocaleTimeString()}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}

        {activeTab === 'metrics' && (
          <div className="space-y-6">
            {/* 自定义指标控制 */}
            <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
              <h2 className="mb-4 text-lg font-semibold">自定义指标管理</h2>

              <div className="mb-4 grid grid-cols-1 gap-4 md:grid-cols-3">
                <div>
                  <label className="mb-2 block text-sm font-medium">
                    指标名称
                  </label>
                  <input
                    type="text"
                    value={metricName}
                    onChange={e => setMetricName(e.target.value)}
                    placeholder="输入指标名称"
                    className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
                  />
                </div>
                <div>
                  <label className="mb-2 block text-sm font-medium">
                    指标值
                  </label>
                  <input
                    type="number"
                    value={metricValue}
                    onChange={e => setMetricValue(e.target.value)}
                    placeholder="输入数值"
                    className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
                  />
                </div>
                <div className="flex items-end">
                  <button
                    onClick={handleSetMetric}
                    disabled={!metricName.trim() || !metricValue.trim()}
                    className="w-full rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:opacity-50"
                  >
                    设置指标
                  </button>
                </div>
              </div>
            </div>

            {/* 当前指标 */}
            <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
              <h2 className="mb-4 text-lg font-semibold">当前自定义指标</h2>

              {metrics?.custom_metrics &&
              Object.keys(metrics.custom_metrics).length > 0 ? (
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
                  {Object.entries(metrics.custom_metrics).map(
                    ([name, value]) => (
                      <div
                        key={name}
                        className="rounded-lg bg-gray-50 p-4 dark:bg-gray-700"
                      >
                        <div className="flex items-center justify-between">
                          <div>
                            <div className="font-medium">{name}</div>
                            <div className="text-2xl font-bold text-blue-600">
                              {value.toFixed(2)}
                            </div>
                          </div>
                          <button
                            onClick={() => handleIncrementMetric(name)}
                            className="rounded bg-green-600 px-2 py-1 text-sm text-white hover:bg-green-700"
                          >
                            +1
                          </button>
                        </div>
                      </div>
                    )
                  )}
                </div>
              ) : (
                <p className="text-gray-500 dark:text-gray-400">
                  没有自定义指标
                </p>
              )}
            </div>
          </div>
        )}

        {activeTab === 'report' && (
          <div className="space-y-6">
            <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
              <div className="mb-4 flex items-center justify-between">
                <h2 className="text-lg font-semibold">性能报告</h2>
                <div className="flex space-x-2">
                  <button
                    onClick={generateReport}
                    className="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
                  >
                    生成报告
                  </button>
                  <button
                    onClick={clearData}
                    className="rounded bg-red-600 px-4 py-2 text-white hover:bg-red-700"
                  >
                    清除数据
                  </button>
                </div>
              </div>

              {report ? (
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
                    <div className="text-center">
                      <div className="text-2xl font-bold text-blue-600">
                        {report.avg_cpu_usage.toFixed(1)}%
                      </div>
                      <div className="text-sm text-gray-600 dark:text-gray-400">
                        平均 CPU
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-green-600">
                        {(report.avg_memory_usage / 1024 / 1024).toFixed(1)}MB
                      </div>
                      <div className="text-sm text-gray-600 dark:text-gray-400">
                        平均内存
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-purple-600">
                        {report.total_events}
                      </div>
                      <div className="text-sm text-gray-600 dark:text-gray-400">
                        总事件数
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-orange-600">
                        {report.active_events_count}
                      </div>
                      <div className="text-sm text-gray-600 dark:text-gray-400">
                        活跃事件
                      </div>
                    </div>
                  </div>

                  {Object.keys(report.event_stats).length > 0 && (
                    <div>
                      <h3 className="mb-2 font-medium">事件统计</h3>
                      <div className="space-y-2">
                        {Object.entries(report.event_stats).map(
                          ([name, stats]) => (
                            <div
                              key={name}
                              className="flex items-center justify-between rounded bg-gray-50 p-2 dark:bg-gray-700"
                            >
                              <span>{name}</span>
                              <span className="text-sm text-gray-600 dark:text-gray-400">
                                {stats.count} 次, 平均{' '}
                                {stats.avg_duration.toFixed(1)}ms
                              </span>
                            </div>
                          )
                        )}
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <p className="text-gray-500 dark:text-gray-400">
                  点击"生成报告"查看性能分析
                </p>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Performance;
